package com.seed.uaa.util;

import cn.hutool.core.util.StrUtil;
import com.seed.core.enumeration.SqlOp;
import com.seed.core.query.pojo.Searched;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class SearchUtil {

    public static List<String> getSearches(List<String> searches, Map<String, String> searchParams) {
        List<String> ret = new ArrayList<>();
        for(String search: searches) {
            String[] items = search.split("=");
            String pathAndOp = items[0];
            String value = items.length > 1 ? items[1] : null;

            int pos = pathAndOp.lastIndexOf('_');
            String finalColumn = pathAndOp.substring(0, pos);
            SqlOp op = SqlOp.valueOf(pathAndOp.substring(pos + 1));
            if(op.equals(SqlOp.isNull) || op.equals(SqlOp.isNotNull)) {
                ret.add(String.format("%s_%s", finalColumn, op.name()));
            } else if(value == null) {
                value = searchParams.get(pathAndOp);
                if(StrUtil.isNotBlank(value)) ret.add(String.format("%s=%s", pathAndOp, value));
                // 客户端没提供值的忽略掉
            } else {
                ret.add(search);
            }
        }
        return ret;
    }

    public static Map<String, Searched> merge(Map<String, Searched> searcheds, Map<String, Searched> others) {
        boolean isSearchedsEmpty = searcheds == null || searcheds.isEmpty();
        boolean isOthersEmpty = others == null || others.isEmpty();

        if(isSearchedsEmpty && isOthersEmpty) return new LinkedHashMap<>();

        if(isSearchedsEmpty) return others;
        if(isOthersEmpty) return searcheds;

        for(Map.Entry<String, Searched> entry: others.entrySet()) {
            String key = entry.getKey();
            Searched searched = searcheds.get(key);
            Searched other = entry.getValue();
            if(searched == null) {
                searcheds.put(key, other);
                continue;
            }

            if(!searched.getType().equals(other.getType())) {
                throw new RuntimeException("类型不匹配");
            }

            merge(searched, other);
        }

        return searcheds;
    }
}
